package synchronized同步语句块1;



//解决问题
//synchronized方法是对当前对象加锁，而synchronized代码块是对某一个对象加锁

class Task{
	private String getData1;
	private String getData2;
	synchronized public void doLongTimeTask(){
		
		try {
			
			System.out.println("begin task");
			Thread.sleep(3000);
			getData1="长时间处理任务后从远程返回的值1 threadName = "+Thread.currentThread().getName();
			getData2="长时间处理任务后从远程返回的值2 threadName = "+Thread.currentThread().getName();
			System.out.println(getData1);
			System.out.println(getData2);
			System.out.println("end task");
		}catch(InterruptedException e)
		{
			e.printStackTrace();
		}
		
	}
}
 class CommonUtils{
	public static  long beginTime1;
	public static long endTime1;
	public static long beginTime2;
	public static long endTime2;
	
}
class Mythread1 extends Thread{
	private Task task;
	public Mythread1(Task task){
		super();
		this.task=task;
	}
	public void run()
	{
		super.run();
		CommonUtils.beginTime1=System.currentTimeMillis();
		task.doLongTimeTask();
		CommonUtils.endTime1=System.currentTimeMillis();
	}
}
class MyThread2 extends Thread{
	private Task task;
	public MyThread2(Task task)
	{
		super();
		this.task=task;
	}
	public void run()
	{
		super.run();
		CommonUtils.beginTime2=System.currentTimeMillis();
		task.doLongTimeTask();
		CommonUtils.endTime2=System.currentTimeMillis();
	}
}
//
public class Test2_20 {
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Task task=new Task();
		Mythread1 thread1=new Mythread1(task);
		thread1.start();
		MyThread2 thread2=new MyThread2(task);
		thread2.start();
		try {
			Thread.sleep(10000);
			
		}catch(InterruptedException e) {
		
			e.printStackTrace();
		}
		long beginTime = CommonUtils.beginTime1;
		if(CommonUtils.beginTime1>CommonUtils.beginTime2) {
			beginTime=CommonUtils.beginTime2;
		}
		long endTime = CommonUtils.endTime1;
		if(CommonUtils.endTime1<CommonUtils.endTime2) {
			endTime=CommonUtils.endTime2;
		}
		System.out.println("耗时：" + (endTime-beginTime));
		
	}

}
